package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Override
    public String upload(MultipartFile file) throws Exception {
        String filename = UUID.randomUUID().toString().replace("-", "") + "_" + file.getOriginalFilename();
        InputStream fis = file.getInputStream();
        //1、创建客户端：使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient
                ("http://192.168.200.100:9000",
                        "admin",
                        "admin123456");

        //2、检查桶是否存在
        boolean isExist = minioClient.bucketExists("mall");
        if (isExist) {
            System.out.println("桶存在.可以上传...");
        } else {
            // 3、不存在可以创建
            minioClient.makeBucket("mall");
        }

        //4、上传：使用putObject上传一个文件到存储桶中。
        /**
         * String bucketName,
         * String objectName,
         * InputStream stream,
         * PutObjectOptions options: 上传参数
         */
        //上传参数  long objectSize, long partSize
        PutObjectOptions options = new PutObjectOptions(file.getSize(), -1L);
        minioClient.putObject("mall", filename, fis, options);
        // 文件地址
        String url = "http://192.168.200.100:9000/mall/" + filename;
        return url;
    }
}
